package com.mall.author.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mall.author.service.LoginService;
import com.mall.author.vo.LoginVo;
import com.mall.author.vo.RegistryVo;
import com.mall.common.constant.AuthorConstant;
import com.mall.common.dto.MemberDTO;
import com.mall.common.exception.ValidationException;
import com.mall.common.utils.Constant;
import com.mall.common.utils.Result;
import com.mall.common.validator.ValidatorUtils;
import com.mall.common.validator.group.AddGroup;
import com.mall.common.validator.group.DefaultGroup;
import com.mall.common.vo.UserInfoVo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 谢君臣
 * @Date: 2022/8/6-16:23
 * @version: 1.0
 * @function:
 */
@Controller
@RequestMapping("/author/login")
public class LoginController {

    @Resource
    private LoginService loginService;

    @GetMapping("/sms/code")
    @ResponseBody
    public Result getSmsCode(@RequestParam("phone")String phone){
        return loginService.getSmsCode(phone);
    }

    @PostMapping("/registry")
    public String registry( RegistryVo registryVo, Model model){
        //效验数据
        try {
            ValidatorUtils.validateEntity(registryVo, AddGroup.class);
            // 校验账户，手机号
            HashMap<String, String> result = loginService.registry(registryVo);
            if (result!=null){
                model.addAttribute("errors",result);
                return "registry";
            }
            // 注册成功
            return "redirect:http://author.mall.com/login";
        } catch (ValidationException e) {
            model.addAttribute("errors",e.getData());
            return "registry";
        }
    }

    @PostMapping("/login_pwd")
    public String login(LoginVo loginVo, HttpSession session, Model model){
        try {
            ValidatorUtils.validateEntity(loginVo,AddGroup.class);
            Result result = loginService.login_pwd(loginVo);
            if (result.getCode()==0){
                // todo session 共享问题
                UserInfoVo userInfo = JSON.parseObject(JSON.toJSONString(result.getData()), new TypeReference<UserInfoVo>(){});
                session.setAttribute(AuthorConstant.LOGIN_USER,userInfo);
                return "redirect:http://mall.com";
            }
            else {
                model.addAttribute("errors",result.getMsg());
                return "login";
            }
        } catch (ValidationException e) {
            model.addAttribute("errors",e.getMsg());
            return "login";
        }
    }

}
